package jehc.djshi.oauth.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jehc.djshi.common.annotation.NeedLoginUnAuth;
import jehc.djshi.common.base.BaseAction;
import jehc.djshi.common.base.BaseHttpSessionEntity;
import jehc.djshi.common.base.BaseResult;
import jehc.djshi.common.entity.LoginEntity;
import jehc.djshi.common.entity.OauthAccountEntity;
import jehc.djshi.common.entity.OauthAdminSysEntity;
import jehc.djshi.common.entity.index.*;
import jehc.djshi.common.util.MD5;
import jehc.djshi.common.util.ExceptionUtil;
import jehc.djshi.common.util.JsonUtil;
import jehc.djshi.common.util.SortUtil;
import jehc.djshi.common.util.StringUtil;
import jehc.djshi.oauth.model.OauthAccount;
import jehc.djshi.oauth.service.OauthAccountService;
import jehc.djshi.oauth.service.OauthSysModeService;
import jehc.djshi.oauth.util.OauthUtil;
import jehc.djshi.oauth.model.OauthResources;
import jehc.djshi.oauth.model.OauthSysModules;
import jehc.djshi.oauth.service.OauthResourcesService;
import jehc.djshi.oauth.service.OauthSysModulesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
 * @Desc 授权中心主页API
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@RestController
@Api(value = "授权中心主页API",tags = "授权中心主页API",description = "授权中心主页API")
public class OauthIndexController extends BaseAction {
    @Autowired
    private OauthResourcesService oauthResourcesService;
    @Autowired
    private OauthSysModulesService oauthSysModulesService;
    @Autowired
    private OauthUtil oauthUtil;
    @Autowired
    private OauthAccountService oauthAccountService;

    @Autowired
    private OauthSysModeService oauthSysModeService;
    /**
     * 初始化主页面
     * @param request
     * @return
     */
    @PostMapping(value="/init")
    @NeedLoginUnAuth
    @ApiOperation(value="初始化主页面", notes="初始化主页面")
    public BaseResult init(HttpServletRequest request){
        String info = oauthUtil.getTokenInfo(request);
        BaseHttpSessionEntity baseHttpSessionEntity = JsonUtil.fromAliFastJson(info, BaseHttpSessionEntity.class);
        String oauthAdminSysEntity = baseHttpSessionEntity.getOauthAdminSysEntities();
        List<OauthAdminSysEntity> oauthAdminSysEntities = JsonUtil.toFList(oauthAdminSysEntity, OauthAdminSysEntity.class);

        List<OauthResources> oauthResourcesList = null;
        List<String> idList = commonSysModulesId(oauthAdminSysEntities);
        Map<String, Object> condition = new HashMap<String, Object>();
        if(null != idList && !idList.isEmpty()){
            //各子系统管理员拥有的资源模块
            condition.put("resources_module_id",idList);
            oauthResourcesList = oauthResourcesService.getOauthResourcesListByCondition(condition);
        }else{
            //各子系统角色
            if(null == baseHttpSessionEntity){
                condition.put("role_id", "-1".split(","));
            }else{
                String xt_role_id = baseHttpSessionEntity.getRole_id();
                if(!StringUtils.isEmpty(xt_role_id)){
                    condition.put("role_id", xt_role_id.split(","));
                }else{
                    condition.put("role_id", "-1".split(","));
                }
            }
            oauthResourcesList = oauthResourcesService.getResourcesListForRole(condition);
        }

        InitAdminPage initAdminPage = new InitAdminPage();

        SortUtil<OauthResources> sortUtil = new SortUtil<OauthResources>();

        sortUtil.Sort(oauthResourcesList, "resources_sort", "asc");

        String json = JsonUtil.toFastJson(oauthResourcesList);

        List<ResourceEntity> resourceEntities = JsonUtil.toFList(json, ResourceEntity.class);

        Map<String,List<ResourceEntity>> map = commonResourceEntities(resourceEntities);//转换资源集合

        if(!CollectionUtils.isEmpty(map)){
            Iterator<Map.Entry<String, List<ResourceEntity>>> entries = map.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry<String, List<ResourceEntity>> entry = entries.next();
                IndexTree tree = new IndexTree(entry.getValue());
                MenuEntity menuEntity = new MenuEntity();
                menuEntity.setSys_mode_id(entry.getKey());
                menuEntity.setSys_mode_icon(entry.getValue().get(0).getSys_mode_icon());
                menuEntity.setSysname(entry.getValue().get(0).getSysname());
                menuEntity.setSys_mode_url(entry.getValue().get(0).getSys_mode_url());
                menuEntity.setMenuList(tree.buildTree(false));
                menuEntity.setSort(entry.getValue().get(0).getMode_sort());
                initAdminPage.getMenuEntity().add(menuEntity);
            }
        }

        sortUtil.Sort(initAdminPage.getMenuEntity(), "sort", "ASC");
        AdminTree adminTree = new AdminTree(resourceEntities);
        initAdminPage.setAdminMenuList(adminTree.buildTree());

        initAdminPage.setBasePath(request.getContextPath());

        initAdminPage.setOauthAccountEntity(getXtU());//当前用户
        return outDataStr(initAdminPage);
    }

    /**
     *
     * @param resourceEntities
     */
    public  Map<String,List<ResourceEntity>> commonResourceEntities(List<ResourceEntity> resourceEntities){
        Map<String,List<ResourceEntity>> map = new HashMap<>();
        if(null!=resourceEntities && !resourceEntities.isEmpty()){
            for(ResourceEntity resourceEntity:resourceEntities){
                List<ResourceEntity> resourceEntityList = map.get(resourceEntity.getSys_mode_id());
                if(null == resourceEntityList || resourceEntityList.isEmpty()){
                    resourceEntityList =  new ArrayList<>();
                }
                resourceEntityList.add(resourceEntity);
                map.put(resourceEntity.getSys_mode_id(),resourceEntityList);
            }
        }
        return map;
    }

    /**
     *
     * @param oauthAdminSysEntities
     * @return
     */
    public List<String> commonSysModulesId(List<OauthAdminSysEntity> oauthAdminSysEntities){
        List<String> idList = new ArrayList<>();
        List<String> sysmodeIdList = new ArrayList<>();
        if(oauthAdminSysEntities == null || oauthAdminSysEntities.isEmpty() || oauthAdminSysEntities.size() == 0){
            return idList;
        }
        for(OauthAdminSysEntity oauthAdminSysEntity : oauthAdminSysEntities){
            sysmodeIdList.add(oauthAdminSysEntity.getSysmode_id());
        }
        if(null == sysmodeIdList || sysmodeIdList.isEmpty() || sysmodeIdList.size() == 0){
            return idList;
        }

        Map<String,Object> condition = new HashMap<>();
        condition.put("sysmode_id",sysmodeIdList);
        List<OauthSysModules> oauthSysModulesList = oauthSysModulesService.getOauthSysModulesListByCondition(condition);
        for(OauthSysModules oauthSysModules:oauthSysModulesList){
            idList.add(oauthSysModules.getSys_modules_id());
        }
        return idList;
    }


    /**
     * 解锁
     * @param loginEntity
     * @return
     */
    @PostMapping(value="/unlock")
    @NeedLoginUnAuth
    @ApiOperation(value="解锁", notes="解锁")
    public BaseResult unlock(@RequestBody(required=true)LoginEntity loginEntity,HttpServletRequest request){
        String password = loginEntity.getPassword();
        if(StringUtil.isEmpty(password)){
            throw new ExceptionUtil("未能获取到密码！");
        }
        OauthAccountEntity oauthAccountEntity = getXtU();
        MD5 md5 = new MD5();
        password = md5.getMD5ofStr(password.trim());
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("password", password);
        condition.put("account", oauthAccountEntity.getAccount());
        condition.put("sys_mode_id",oauthSysModeService.getSysModeId(request));
        OauthAccount oauthAccount = oauthAccountService.login(condition);
        if(null != oauthAccount){
            return outAudStr(true,"1");
        }else{
            return outAudStr(true,"2");
        }
    }
}
